package com.kuang.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kuang.blog.entity.Blog;
import com.kuang.blog.entity.User;
import com.kuang.blog.service.BlogService;
import com.kuang.blog.util.Result;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.PublicKey;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 开发者：HaoZhong
 * @since 2022-09-27
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Resource
    private BlogService blogService;

    /**
     * 查询所有
     * @return
     */

    @GetMapping("retrieveAll")
    public Result retrieveAll(){
        QueryWrapper<Blog> wrapper = new QueryWrapper<Blog>();
        List<Blog> list = blogService.list(wrapper);
           return Result.success(list);
    }
    /**
     * 分页查询
     * @return
     */

    @PostMapping("retrievePage")
    public Result retrievePage(@RequestBody Page page){
        //示例json参数
        // {
        //    "size": 5,
        //    "current":
        //}
        QueryWrapper<Blog> wrapper = new QueryWrapper<Blog>();
        IPage page1 = blogService.page(page,wrapper);
        return Result.success(page1);
    }
/**
 * 根据id查询
 */

@GetMapping("/retrieveById/{id}")
public Result retriveById(@PathVariable("id")int id){
    Blog blog = blogService.getById(id);
    return Result.success(blog);
}
    /**
     * 根据标题模糊查询
     */

    @RequestMapping("/retrieveLike")
    public Result retrieveLike(@RequestBody Blog blog){
        QueryWrapper<Blog> wrapper = new QueryWrapper<Blog>();
        wrapper.like("title",blog.getTitle());
        List<Blog> list = blogService.list(wrapper.orderByDesc("created"));
        return Result.success(list);
    }
    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequiresAuthentication
    @DeleteMapping("/delete/{id}")
    public boolean deleteById(@PathVariable int id){
        return blogService.removeById(id);
    }

    /**
     * 新增
     * @param blog
     * @return
     */
    @RequiresPermissions("create")
    @PostMapping("/create")
    public boolean create(@RequestBody Blog blog){
        return blogService.save(blog);
    }
    /**
     * 修改
     */

    @PutMapping("/update")
    @RequiresPermissions("update")
    public boolean update(@RequestBody Blog blog){
        return blogService.updateById(blog);
    }
}

